<template>
  <el-tabs class="p-20 w-full h-full" tab-position="left" v-loading="state.loading">
    <el-tab-pane label="基本设置">
      <el-page-header class="detail-header">
        <template #icon>
          <el-icon size="22">
            <User/>
          </el-icon>
        </template>
        <template #title>
          <h2>基本信息</h2>
        </template>
        <template #extra>
          <div style="flex: auto">
            <el-button type="primary" @click="handleOk(formRef)" class="w-100" :loading="state.loading" :icon="Select">
              保存
            </el-button>
          </div>
        </template>
      </el-page-header>
      <div class="detail-form">
        <el-form ref="formRef" :model="formState" :rules="rules" v-loading="state.loading" label-width="auto" label-position="right">
          <el-row :gutter="20">
            <el-col :span="10" :offset="1">
              <el-form-item prop="image" label="头像" label-position="right">
                <img-upload ref="avatarRef" id="avatar" @uploadSuccess="handleUploadSuccess"
                            @removeImg="handleUploadRemove" :fileType="'avatar'"
                            :file-path="formState.image" :upload-type="Upload.TYPE.AVATAR"
                            :style="{width: '100px', height: '100px', borderRadius: '50%'}"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="10" :offset="1">
              <el-form-item prop="userName" label="用户名" label-position="right">
                <el-input id="userName" v-model="formState.userName" class="w-full" placeholder="请输入用户名" clearable/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="10" :offset="1">
              <el-form-item prop="mobile" label="联系方式" label-position="right">
                <el-input id="mobile" v-model="formState.mobile" class="w-full" placeholder="请输入联系方式" clearable/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="10" :offset="1">
              <el-form-item prop="email" label="邮箱" label-position="right">
                <el-input id="email" v-model="formState.email" class="w-full" placeholder="请输入邮箱" clearable/>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </el-tab-pane>
    <el-tab-pane label="安全设置">
      <el-page-header class="detail-header">
        <template #icon>
          <el-icon size="22">
            <Key/>
          </el-icon>
        </template>
        <template #title>
          <h2>修改密码</h2>
        </template>
        <template #extra>
          <div style="flex: auto">
            <el-button type="primary" @click="handleEditPassword(pwdFormRef)" class="w-100" :loading="state.loading"
                       :icon="Select">
              保存
            </el-button>
          </div>
        </template>
      </el-page-header>
      <div class="detail-form">
        <el-form ref="pwdFormRef" :model="formPasswordState" :rules="pwdRules" label-width="auto" label-position="right">
          <el-row :gutter="20">
            <el-col :span="10" :offset="1">
              <el-form-item prop="password" label="新密码" label-position="right">
                <el-input id="password" type="password" v-model="formPasswordState.password" class="w-full"
                          placeholder="请输入新密码" show-password clearable/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="10" :offset="1">
              <el-form-item prop="confirmPassword" label="确认密码" label-position="right">
                <el-input id="confirmPassword" type="password" v-model="formPasswordState.confirmPassword" class="w-full"
                          placeholder="请输入新密码" show-password clearable/>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </el-tab-pane>
  </el-tabs>
</template>
<script setup name="Profile">
import ImgUpload from '@/components/ImgUpload/index.vue';
import {Key, Select, User} from "@element-plus/icons-vue";
import {detailState, state, setLoading, rules, rePasswordState} from "@/views/profile/index.js";
import {UserApi} from "@/api/system/user/index.js";
import {CacheUtil} from "@/utils/cacheUtil.js";
import useCurrentInstance from "@/hooks/useCurrentInstance.js";
import {Upload} from "@/common/constant.js";
import {CommonApi} from "@/api/common.js";
import {JSEncrypt} from "jsencrypt";
import {setSubLoading} from "@/views/system/user/index.js";

const {proxy} = useCurrentInstance()
const formRef = ref();
let formState = toRef(detailState);
const pwdFormRef = ref();
let formPasswordState = toRef(rePasswordState);

let validatePassForm = (rule, value) => {
  if (value === "") {
    return Promise.reject("请输入密码");
  }
  if (value.length < 6 || value.length > 16) {
    return Promise.reject("密码长度必须在6到16个字符之间");
  }
  if (!/[0-9]/.test(value) || !/[a-zA-Z]/.test(value)) {
    return Promise.reject("密码必须包含数字和字母");
  }
  return Promise.resolve();
}

let validateConfirmPassForm = (rule, value) => {
  if (value === "") {
    return Promise.reject("请再次输入密码");
  } else if (value !== formPasswordState.value.password) {
    return Promise.reject('两次输入密码不一致!');
  }
  return Promise.resolve();
}

const pwdRules = reactive({
  password: [{required: true, validator: validatePassForm, trigger: 'blur'}],
  confirmPassword: [{required: true, validator: validateConfirmPassForm, trigger: 'blur'}],
})

//上传图片
function handleUploadSuccess(imgUrl, fileType) {
  if (fileType === 'avatar') {
    formState.value.image = imgUrl;
  }
}

function handleUploadRemove(fileType) {
  if (fileType === 'avatar') {
    formState.value.image = '';
  }
}

function handleEditPassword(formEl) {
  if (!formEl) return
  formEl.validate(async (valid, fields) => {
    if (valid) {
      setLoading(true)
      const result = await CommonApi.getPublicKey();
      if (result) {
        const {publicKey, sessionGenerateId} = result;
        CacheUtil.setSessionGenerateId(sessionGenerateId);
        const encryptor = new JSEncrypt();
        encryptor.setPublicKey(publicKey);
        if (formPasswordState.value.password !== formPasswordState.value.confirmPassword) {
          proxy.$message.error('两次密码不一致');
          setLoading(false);
          return;
        }
        const password = encryptor.encrypt(formPasswordState.value.password);
        UserApi.rePassword({id: formState.value.id, password, confirmPassword: password}).then(res => {
          if (res.success) {
            proxy.$message.success('密码修改成功,请重新登录');
            pwdFormRef.value?.resetFields()
            location.href = '/login'
            CacheUtil.clear()
          }
        }).finally(() => {
          setLoading(false);
        });
      } else {
        proxy.$message.error("操作失败");
      }
      setLoading(false)
    } else {
      console.log('error submit!', fields)
    }
  })
}

function handleOk(formEl) {
  if (!formEl) return
  formEl.validate((valid, fields) => {
    if (valid) {
      setLoading(true)
      if (formState.value.id) {
        formState.value.password = null
        UserApi.update(formState.value).then(res => {
          if (res.success) {
            proxy.$message.success(res.msg)
          }
        }).finally(() => {
          setSubLoading(false);
        });
      }
      setLoading(false)
    } else {
      console.log('error submit!', fields)
    }
  })
}

function initInfo() {
  setLoading(true);
  UserApi.findById({id: CacheUtil.getUserInfo().id}).then((res) => {
    if (res.success && res.data) {
      formState.value = res.data;
    }
  }).finally(() => {
    setLoading(false);
  })
}

initInfo()
</script>

<style scoped lang="scss">
:deep(.el-tabs .el-tabs__header .el-tabs__nav .el-tabs__active-bar) {
  z-index: 0;
  width: 100%;
  background-color: var(--el-color-primary-light-9);
  border-right: 2px solid var(--el-color-primary);
  transition: transform 0.3s, background-color 0.3s, var(--el-transition-border);
}

:deep(.el-tabs__item.is-active) {
  background-color: var(--el-color-primary-light-9);
}

:deep(.el-tabs__item) {
  padding-right: 100px;
  text-align: left;
}

:deep(.el-tab-pane) {
  padding: 0 20px 0 30px;
}

.detail-header {
  padding: 10px;
  border-bottom: 1px solid #ebeef5;
}

.detail-form {
  padding: 20px 5px;
  height: 100%;
  overflow-y: auto;
  overflow-x: hidden;
}

</style>
